<style lang="less">
@import "login.less";
</style>
<template>
  <div class="all" style="width: 100%;height: 100%;position: relative;">
    <div class="box_1">
      <span class="text_1">经济发展指标监测分析信息管理系统</span>
    </div>

    <div class="login" @keydown.enter="handleSubmit2">

      <img src="./img/99.png" alt="" srcset="" />

      <div class="burl"></div>

      <!--       账号密码登录-->
      <div class="login-con" v-if="thirdType === ''">
        <div class="card" style="width: 100%;height: 100%">
          <div class="login-body">
            <!--            <img class="logo" src="./login-logo.png"/>-->
            <span class="title-span">欢迎登录</span>

            <Form ref="loginForm" :model="form" :rules="rules" style="margin-top: 7px">
              <FormItem prop="userName">
                <i-input v-model="form.userName" placeholder="请输入用户名" autocomplete="off"
                  class="input">
                  <span slot="prepend">
                    <img src="./img/beifen1.png" alt="">
                  </span>
                </i-input>
              </FormItem>
              <FormItem prop="password">
                <i-input type="password" v-model="form.password" placeholder="请输入密码" autocomplete="off"
                  class="input">
                  <span slot="prepend">
                    <img src="./img/beifen2.png" alt="">
                  </span>
                </i-input>
              </FormItem>
              <!-- 验证码 -->
              <FormItem v-if='!Setting.captchaTypeCode'>
                <SecurityCode :value.sync="value" :biyiCaptchaKey.sync="biyiCaptchaKey" width="437" ref="securityCode">
                </SecurityCode>
              </FormItem>

              <!-- 登录按钮 -->
              <Button @click="handleSubmit2" type="primary" long :loading="isLogining"
                class="btn">
                {{ loginBtnText }}
              </Button>
              <!-- <FormItem v-if="Setting.isCas">
                <Select v-model="casOrNormal" transfer @on-change='goToCas'>
                  <Option value="normal">普通登录</Option>
                  <Option value="cas">cas登录</Option>
                </Select>
              </FormItem> -->
            </Form>
          </div>
        </div>
      </div>
    </div>
    <Verify @success='success' :mode="'pop'"
      :captchaType="Setting.captchaTypeCode == 'blockPuzzle' ? 'blockPuzzle' : 'clickWord'"
      :imgSize="{ width: '400px', height: '200px' }" ref="verify"></Verify>
  </div>
</template>

<script>
import SecurityCode from './component/securityCode'
// 引入组件
import Verify from '@/views/admin/components/verifition/Verify'

export default {
  props: {
    Setting: Object,
    cas: Object
  },
  data () {
    return {
      thirdSrc: '',
      thirdType: '',
      isLogining: false,
      loginBtnText: '登录',
      rememberme: null,
      form: {
        userName: '',
        password: '',
        tenantAccount: this.$util.sassModel ? '' : 'default'
      },
      rules: {
        userName: [{
          required: true,
          message: '账号不能为空',
          trigger: 'blur'
        }],
        tenantAccount: [{
          required: true,
          message: '租户账号不能为空',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '密码不能为空',
          trigger: 'blur'
        }]
      },
      value: '',
      biyiCaptchaKey: '',
      casOrNormal: 'normal'
    }
  },
  components: {
    SecurityCode,
    Verify
  },
  methods: {
    handleSubmit2 () {
      // alert("sssss")
      if (this.Setting.captchaTypeCode) {
        // alert('sssss')
        this.useVerify()
      } else {
        this.handleSubmit()
      }
    },
    onThirdLogin (type) {
      let url = ''
      let domain = window.location.origin
      if (type === 'tianyi') {
        url = '/api/system/thirdAuth/tianyi/getUnifyAccountLoginUrl'
        this.$util.http.get(url, { params: { 'state': domain } }).then(res => {
          this.thirdSrc = res.data
          this.thirdType = 'tianyi'
        }).catch(err => {
          console.log(new Error(err))
        })
      } else if (type === 'wechat_enterprise') { // 企业微信
        url = 'api/system/getQrCode'
        this.$util.http.get(url).then(res => {
          this.thirdType = 'wechat_enterprise'
          let netData = res.data.data
          let codeUrl = `https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=${netData.appid}&agentid=${netData.agentid}&redirect_uri=${netData.redirectUri}&state=${domain}`
          this.thirdSrc = codeUrl
        }).catch(err => {
          console.log(new Error(err))
        })
      }
    },
    success (params) {
      // params 返回的二次验证参数, 和登录参数一起回传给登录接口，方便后台进行二次验证
      // captchaVerification: "0EgmmvFSvxXkL5WuuZ2WPxeAlRdeSEk4zVxVqPq+1HRUsM4a1rz+DbYD+42DEWl3fIrPfYJhK+fe6IU0G6ZPM/oJHOk+m5BsUombAcgcI7GzagFxd6cwPUBPmnLaJ+Eh"
      // captchaVerification: "A6RH3i1Y8db+GQtz82YTmaix+7jgo8KBZ8EkRjmyz832vVc/nalGSiT7p6CRDCrFmyWLzqnkJGfIqFbIFK8Aanw2Wj3KZT238J7ivryX+pE="
      if (params.captchaVerification) {
        this.handleSubmit(params.captchaVerification)
      }
      // console.log('========>', params)
    },
    useVerify () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$refs.verify.show()
        }
      })
    },
    setRememberMe (value) {
      if (value) {
        localStorage['rememberme'] = 1
      } else {
        localStorage['rememberme'] = 0
      }
    },
    handleSubmit (param) {
      this.$refs.loginForm.validate((valid) => {
        // 默认字符验证码
        if (!this.Setting.captchaTypeCode) {
          var reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
          if (reg.test(this.value)) {
            this.$Message.error({
              content: `登录失败，验证码不允许存在中文！`
            })
            return
          }
        }
        // console.log('++++++++++', param)

        if (valid) {
          this.isShowModal = true
          this.isLogining = true
          let msg = this.$Message.loading({
            content: '正在登录中',
            duration: 0
          })
          var pswd = this.$util.encryptPassword
            ? this.$util.encryptPassword(this.form.password)
            : this.form.password

          const [url, data, config] = [
            '/api/system/login',
            {
              username: this.form.userName,
              password: pswd,
              tenantAccount: this.form.tenantAccount,
              rememberme: localStorage['rememberme']
            },
            {
              headers: {
                biyiCaptchaKey: this.biyiCaptchaKey,
                biyiCaptcha: JSON.stringify({
                  code: this.value
                }),
                captchaVerification: (typeof param) === 'string' ? param : ''
              }
            }
          ]
          this.$http.post(url, data, config).then((response) => {
            msg()
            this.isLogining = false
            console.log(response, 'respdonse')
            if (
              this.$route.meta.validatePaswd &&
              response.data.passwordStatus
            ) {
              this.$Message.warning({
                content:
                  response.data.passwordStatus === 1
                    ? '初始密码强度较弱，请修改后再重新登录！'
                    : '密码已使用3个月，请修改后再重新登录！'
              })
              this.$byStoreSet('user-info', this.form)
              this.$router.push({ name: 'update-password' })
            } else {
              localStorage.token = response.data.token
              this.$Message.success({
                content: '登录成功！',
                onClose: () => {
                  this.$router.replace('/ImportExcel')
                }
              })
            }
          })
            .catch((error) => {
              msg()
              if (!this.Setting.captchaTypeCode) {
                this.$refs.securityCode.init()
              }
              this.isLogining = false
              if (error.response) {
                switch (error.response.status) {
                  case 401:
                    if (error.response.data.attempts) {
                      this.$Message.error(
                        `登录失败，您还有 ${error.response.data.attempts} 尝试机会！`
                      )
                    } else {
                      const locktime = this.formatLockedTime(
                        error.response.data.lockoutTime
                      )
                      this.$Message.error({
                        content: `登录失败，您的账号已被锁定，请在<span style="font-weight: bold; color: #2d8cf0;">${locktime}</span>后重试！`
                      })
                    }
                    break
                  default:
                    // this.$Message.error(
                    //   `登录失败，${error.response.data.title}！`
                    // )
                    this.$Message.error(
                      `登录失败，用户名或密码错误！`
                    )
                    break
                }
              }
            })
        }
      })
    },
    formatLockedTime (time) {
      let str = ''
      const d = parseInt(time / (3600 * 24))
      let h = parseInt((time % (3600 * 24)) / 3600)
      let m = parseInt((time % 3600) / 60)
      let s = (time % 3600) % 60
      if (d > 0) {
        str = `${str}${d}天`
      }
      if (h > 0) {
        str = `${str}${h}小时`
      }
      if (m > 0) {
        str = `${str}${m}分`
      }
      if (s > 0) {
        str = `${str}${s}秒`
      }
      return str
    },
    goToCas (value) {
      if (value === 'cas') {
        this.cas.login()
      }
    }
  },
  created () {
    // this.getlogin()
    this.$store.commit('user/logout')
    let dom = document.querySelector('.biyi-style')
    if (dom) {
      dom.remove()
    }
    localStorage.removeItem('biyi-theme')
    if (!localStorage['rememberme']) {
      localStorage['rememberme'] = 0
    }
    this.rememberme = !(localStorage['rememberme'] === '0')
  }
}
</script>
<style>
html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}
</style>
<style lang="less" scoped>
.all {
  background-image: url(./img/bj.png);
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
}

.box_1 {
  height: 133px;
  background: url(./img/toubu.png) -1px 15px no-repeat;
  background-position: center;
  background-size: cover;
  width: 100%;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;

  .text_1 {
    margin-top: -45px;
    color: #FFFFFF;
    font-size: 40px;
  }
}

.login {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  position: relative;
  align-items: center;
  text-align: left;
  display: flex;
  justify-content: space-around;

  .burl {
    //position: absolute;
    //right: 160px;
    //top: 20%;
    //transform: translateY(-50%);
    margin-right: 160px;
    width: 448px;
    height: 526px;
    // background: inherit;
    // filter: blur(8px);
  }

  &-con {
    position: absolute;
    right: 160px;
    background-image: url(./img/kuang.png);
    top: 50%;
    transform: translateY(-50%);
    width: 546px;
    height: 516px;
    z-index: 10;
  }

  &-body {
    // width: 448px;
    // height: 526px;
    width: 546px;
    height: 516px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .title-span {
      font-weight: Heavy;
      font-size: 34px;
      color: #FFFFFF;
      margin-bottom: 18px;
    }
  }
}

.input {
  width: 437px;
  height: 52px;
}

.card {
  width: 448px;
  height: 526px;
  // background: rgba(255, 255, 255, 0.6);
  border-radius: 16px 16px 16px 16px;
  opacity: 1;
}

::v-deep .ivu-input-group-prepend {
  width: 52px;
  border: 1px solid #3C90F3;
  border-right: 0;
  background-color: rgba(62, 112, 151, 0.43);
}

::v-deep .ivu-input {
  background: rgba(62, 112, 151, 0.43);
  border-radius: 3px 3px 3px 3px;
  opacity: 1;
  border: 1px solid #3C90F3;
  height: 100%;
  color: #FFFFFF;
  font-size: 20px;
  caret-color: #3C90F3;

}

.sfImgBox {
  display: flex;
  align-items: center;
  justify-content: space-between;

}

.btn {
  height: 56px;
  background-size: 100% 100%;
  width: 435px;
}

.ivu-checkbox-wrapper {
  margin: 0 !important;
}
</style>
